/**
 * 佣金管理
 */
define(function(require, exports, module) {
    var $ = require("jquery");
    var angular = require("angular");
    require("angular-route");
    require("angular-ui");
    require("angular-interceptor");
    require("pagination");
    var util = require("util");
    require("./common");
    var Template = require("/public/js/lib/template");
    var Highcharts = require("/public/js/lib/highcharts/js/highcharts");

    var app = angular.module('app', ['ngRoute', 'ngUI', 'ngInterceptor', 'commonModule']);

    // 查询服务
    function queryService($http, $q, baseData) {
        var service = {
            // 是否有数据
            hasData: true,
            // 图表周期
            amountChartCycle: '1',
            // 图表周期
            countChartCycle: '1',
            // 明细周期
            detailCycle: '1',
            // 成交类型：认购 7、签约 8
            dealType: '7',
            // 成交类型文本
            dealTypeText: function() {
                return service.dealType == '7' ? '认购' : '签约';
            },

            // =======================数据转化 start====================================
            convertData: function (data) {
                var i = 0, j, len = data.length, length = 0,
                    custData = {}, series = [], n = -1,
                    categories = [], temp, tempData;

                for (; i < len; i++) {
                    series[i] = {};
                    series[i]['name'] = data[i]['projName'];
                    series[i]['data'] = [];
                    series[i]['color'] = baseData.colorArray[i];
                    tempData = data[i]['data'];

                    for (j = 0, length = tempData.length; j < length; j++) {
                        if (i === 0) {
                            categories.unshift(tempData[j]['xdate']);
                        }

                        temp = tempData[j]['cj_count'];
                        if (temp == undefined) {
                            temp = tempData[j]['cj_price'];
                        }
                        temp = parseFloat(temp);
                        series[i]['data'].unshift(temp);
                    }
                }

                custData.step = length > 0 ? Math.ceil(length / 4) : 1;
                custData.maxStaggerLines = 1;
                custData.categories = categories;
                custData.series = series;

                return custData;
            },

            convertData2: function (data) {
                var i = 0, len = data.detail.length, temp, j = 0,
                    custData = {
                        xLen: len,
                        data: [],
                        yLen: 0,
                        projName: [],
                        totalCjCount: [],
                        totalCjPrice: [],
                        rowCount: data.rowCount,
                        typeText: service.dealTypeText()
                    };

                for (; i < len; i++) {
                    temp = data.detail[i].data;
                    i === 0 && (custData.yLen = temp.length);
                    custData.projName.push(data.detail[i].projName);
                    custData.totalCjCount.push(data.detail[i].totalCjCount);
                    custData.totalCjPrice.push(data.detail[i].totalCjPrice);
                    custData.data.push(temp);
                }

                return custData;
            },

            
            // =======================图表数据结构 start======================================
            dataDefault1: {
                chart: {
                    type: 'area',
                    marginTop: 50
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: '金额(万元)',
                    align: 'left'
                },
                xAxis: {
                    categories: [],//['1750', '1800', '1850', '1900', '1950', '1999', '2050'],
                    tickmarkPlacement: 'between',
                    title: {
                        enabled: false
                    },
                    labels: {
                        step: 1 //parseInt(result.length / 5, 10),
                    }
                },
                yAxis: {
                    title: {
                        text: ''
                    },
                    min: 0,
                    gridLineColor: '#EBEBEB'
                },
                legend: {
                    //align: 'right'
                    // x: 150,
                    layout: 'horizontal',
                    align: 'right',
                    verticalAlign: 'top',
                    borderWidth: 0,
                    floating: true,
                    symbolWidth: 12,
                    symbolHeight: 12
                },
                tooltip: {
                    shared: true,
                    valueSuffix: ' 万元'
                },
                plotOptions: {
                    area: {
                        stacking: null,
                        lineWidth: 1,
                        fillOpacity: 0.4
                    }
                },
                credits: { // 版权
                    enabled: false
                },
                series: []/*[{
            name: '项目1',
            color: '#FEBA00',
            data: [502, 635, 809, 947, 1402, 3634, 5268]
        }, {
            name: '项目2',
            color: '#aaa',
            data: [106, 107, 111, 133, 221, 767, 1766]
        }, {
            name: '项目3',
            data: [163, 203, 276, 408, 547, 729, 628]
        }, {
            name: '项目4',
            data: [18, 31, 54, 156, 339, 818, 1201]
        }, {
            name: '项目5',
            data: [2, 2, 2, 6, 13, 30, 46]
        }]*/
            },

            dataDefault2: {
                chart: {
                    type: 'column',
                    marginRight: 30,
                    marginTop: 50
                },
                title: {
                    text: ''
                },
                subtitle: {
                    text: '套数(套)',
                    align:'left'
                },
                xAxis: {
                    categories: [],//['11月5号','11月12号','11月19号','11月26号'],
                    tickmarkPlacement: 'between'
                },
                yAxis: {
                    min: 0,
                    title: {
                        text: ''
                    },
                    gridLineColor: '#EBEBEB'
                },
                plotOptions: {
                    column: {
                        // pointPadding: 0.2
                    }
                },
                tooltip: {
                    valueSuffix: ' 套'
                },
                legend: {
                    // borderWidth: 0,
                    layout: 'horizontal',
                    align: 'right',
                    verticalAlign: 'top',
                    borderWidth: 0,
                    floating: true,
                    symbolWidth: 12,
                    symbolHeight:12
                },
                credits:{ // 版权
                    enabled: false
                },
                series: []/*[{
            name: '移动销售',
            color: '#FEBA00',
            data: [49.9, 71.5, 80.4, 29.2]

        }, {
            name: '全民营销',
            color: "#02828F",
            data: [83.6, 78.8, 88.5, 83.4]

        }]*/
            },
        // =======================图表数据结构 end==================================

            query: function() {
                service.queryAmountChart();
                service.queryCountChart();
                service.queryDetail();
                //service.queryAmountRank();
                //service.queryCountRank();
            },

            // 获取图表数据
            queryAmountChart: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.amountChartCycle = baseData.getValidCycle(service.amountChartCycle);
                filters.type = service.dealType;
                var url = '/api/index.php?r=olap/deal-statistics/get-deal-amount-info-to-list';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.amountChartData = data.data;
                    });
            },

            // 获取图表数据
            queryCountChart: function () {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.countChartCycle = baseData.getValidCycle(service.countChartCycle);
                filters.type = service.dealType;
                var url = '/api/index.php?r=olap/deal-statistics/get-deal-count-info-to-list';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.countChartData = data.data;
                    });
            },

            // 获取明细数据
            queryDetail: function (pageIndex) {
                if (!baseData.loaded) {
                    return null;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                filters.type = service.dealType;
                filters.pageIndex = pageIndex || 1;
                filters.pageSize = service.pageSize;
                var url = '/api/index.php?r=olap/deal-statistics/get-deal-amount-count-detail-info';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.pageIndex = filters.pageIndex;
                        service.total = data.data.rowCount;
                        service.detailData = data.data;
                    });
            },

            // 导出数据
            exportData: function () {
                if (!baseData.loaded) {
                    return;
                }
                var filters = baseData.getFilters();
                if (!filters) {
                    return;
                }
                filters.cycle = service.detailCycle = baseData.getValidCycle(service.detailCycle);
                filters.type = service.dealType;
                var url = '/api/index.php?r=olap/deal-statistics/export';
                util.download(url, filters);
            },

            // 获取明细数据
            queryAmountRank: function () {
                if (!baseData.loaded) {
                    return null;
                }

                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.dealType;
                var url = '/api/index.php?r=olap/deal-statistics/get-top10-deal-amount-info';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.amountRankData = data.data;
                    });
            },

            // 获取明细数据
            queryCountRank: function () {
                if (!baseData.loaded) {
                    return null;
                }

                var filters = baseData.getFilters();
                if (!filters) {
                    return null;
                }
                filters.type = service.dealType;
                var url = '/api/index.php?r=olap/deal-statistics/get-top10-deal-count-info';

                if (arguments.callee.canceller) {
                    // 查询时，如果前面的查询还没完成，把它中止
                    arguments.callee.canceller.resolve();
                }
                arguments.callee.canceller = $q.defer();

                return $http.post(url, filters, { timeout: arguments.callee.canceller.promise })
                    .success(function (data) {
                        service.countRankData = data.data;
                    });
            }
        };

        return service;
    }
    app.factory('query', ['$http', '$q', 'baseData', queryService]);

    function StatisticsController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;
    }
    app.controller('StatisticsController', ['$scope', '$location', 'baseData', 'query', StatisticsController]);

    function SearchController($scope, $location, baseData, query) {
        $scope.baseData = baseData;
        $scope.query = query;

        $scope.$watch('baseData.projectIds', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.query();
            }
        });

        $scope.$watch('query.amountChartCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryAmountChart();
            }
        });

        $scope.$watch('query.countChartCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryCountChart();
            }
        });

        $scope.$watch('query.detailCycle', function (newValue) {
            if (newValue !== undefined && baseData.loaded) {
                query.queryDetail();
            }
        });

        $scope.$watch('query.amountChartData', function (newValue) {
            if (newValue) {
                var data = query.convertData(newValue);
                var chart = new Highcharts.Chart(baseData.mergeLineChartData(query.dataDefault1, {
                    chart: {
                        renderTo: 'graphic_01'
                    },
                    xAxis: {
                        categories: data.categories,
                        labels: {
                            step: data.step
                        },
                        showFirstLabel: false
                    },
                    series: data.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.countChartData', function (newValue) {
            if (newValue) {
                var data = query.convertData(newValue);
                var chart = new Highcharts.Chart(baseData.mergeLineChartData(query.dataDefault2, {
                    chart: {
                        renderTo: 'graphic_02'
                    },
                    xAxis: {
                        categories: data.categories,
                        labels: {
                            step: data.step
                        },
                        showFirstLabel: false
                    },
                    series: data.series
                }));

                setTimeout(function () {
                    chart.reflow();
                }, 0);
            }
        });

        $scope.$watch('query.detailData', function (newValue) {
            if (newValue !== undefined) {
                var data = query.convertData2(newValue);
                var html = Template($('#templ_table').html(), data, baseData.formatData);
                $('#table_content').html(html);
            }
        });
    }
    app.controller('SearchController', ['$scope', '$location', 'baseData', 'query', SearchController]);

    angular.bootstrap(document.getElementById('ng-app'), ['app']);
});